<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <bubble-select-local
            v-model="filterData.appCode"
            labelKey="appName"
            valueKey="appCode"
            :filterable="false"
            style="width: 230px"
            :list="appCodeList"
            placeholder="小程序平台"
            @change="getAxiosData(true)"
          ></bubble-select-local>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="EpRefreshRight" :loading="updateAllCorrectPayTotalAmountLoading" @click="updateAllCorrectPayTotalAmountHandler">
            同步广告收入
          </el-button>
        </div>
      </div>
    </template>
    <div class="statistics-block">
      <div v-for="i in statisticsData" :key="i.flag" class="statistics">
        <div class="title">{{ i.name }}</div>
        <div class="value" :class="{ 'operable': i.type === 'primary' }">{{ i.format(censusData) }}</div>
      </div>
    </div>
    <el-table ref="elTableRef" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column label="日期" prop="thatdayDate" minWidth="120"></el-table-column>
      <el-table-column label="小程序名称" prop="appName" minWidth="180"></el-table-column>
      <el-table-column label="激励金（单位：元）" prop="incentiveFundCost" minWidth="180"></el-table-column>
      <el-table-column label="收入金额（单位：元）" prop="income" minWidth="180"></el-table-column>
      <el-table-column label="收入总金额（单位：元）" prop="totalIncome" minWidth="180"></el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
  </base-load-page>
</template>

<script setup lang="ts">
  import { formatNumberWithMoney } from '@/utils/numb.ts';
  import EpRefreshRight from '~icons/ep/refresh-right';
  import { type AppUserConsumption, getThirdAdvertEverydayIncome, getThirdAdvertEverydayIncomeUpdate, socialList } from '@/api/app-user-management';
  const updateAllCorrectPayTotalAmountLoading = ref(false);

  const { proxy } = getCurrentInstance() as any;
  const dataRange = ref<[string, string] | undefined>();
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const filterData: Ref<any> = ref<any>({
    appCode: undefined,
    current: 1,
    size: 40,
    startDate: undefined,
    endDate: undefined,
  });

  const appCodeList = ref();

  /** 平台类型 */
  const getsocialList = async () => {
    const res = await socialList();
    appCodeList.value = res.data;
  };
  const tableData: Ref<AppUserConsumption[]> = ref([]);
  const description = ref('');
  onMounted(() => {
    dataRange.value = [proxy.$dayjs().subtract(1, 'day').format('YYYY-MM-DD'), proxy.$dayjs().subtract(1, 'day').format('YYYY-MM-DD')];
    getAxiosData();
    getsocialList();
  });

  interface StatisticsItem {
    name: string;
    flag: string;
    type?: string;
    format: (val: Record<string, number>) => number | string;
  }

  /** 同步广告收入 */
  async function updateAllCorrectPayTotalAmountHandler() {
    updateAllCorrectPayTotalAmountLoading.value = true;
    if (Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = `${dataRange.value[0]} 00:00:00`;
      filterData.value.endDate = `${dataRange.value[1]} 23:59:59`;
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    await getThirdAdvertEverydayIncomeUpdate(filterData.value);
    getAxiosData();
    updateAllCorrectPayTotalAmountLoading.value = false;
  }

  /** 统计数据 */
  const censusData = ref<Record<string, number>>({
    totalIncome: 0,
    incentiveFundCost: 0,
    income: 0,
  });
  const statisticsData = ref<StatisticsItem[]>([
    {
      name: '收入总金额',
      flag: 'totalIncome',
      format(val) {
        return formatNumberWithMoney(val?.totalIncome || 0) ?? 0;
      },
    },
    {
      name: '激励金',
      flag: 'incentiveFundCost',
      format(val) {
        return formatNumberWithMoney(val?.incentiveFundCost || 0) ?? 0;
      },
    },
    {
      name: '收入金额',
      flag: 'income',
      format(val) {
        return formatNumberWithMoney(val?.income || 0) ?? 0;
      },
    },
  ]);
  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      if (Array.isArray(dataRange.value) && dataRange.value.length) {
        filterData.value.startDate = `${dataRange.value[0]} 00:00:00`;
        filterData.value.endDate = `${dataRange.value[1]} 23:59:59`;
      } else {
        filterData.value.startDate = '';
        filterData.value.endDate = '';
      }
      const res = await getThirdAdvertEverydayIncome(filterData.value);
      censusData.value.totalIncome = res.data.totalIncome;
      censusData.value.incentiveFundCost = res.data.incentiveFundCost;
      censusData.value.income = res.data.income;
      tableData.value = res.data.page.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.page.current;
      filterData.value.size = res.data.page.size;
      baseData.total = res.data.page.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }
</style>
